﻿using CheemsControl.Animations;
using CheemsControl.Models;
using CheemsControl.Models.MessageTimeline;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;

namespace CheemsControl.Controls
{
    public class MessageTimeline : UserControl
    {
        private MessageDatas _messageDatas;

        public MessageTimeline()
        {
            this.Foreground = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xFF, 0x66, 0x66, 0x66));
        }

        /// <summary>
        /// 数据
        /// </summary>
        public MessageDatas Source
        {
            get { return (MessageDatas)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }
        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(MessageDatas), typeof(MessageTimeline), new PropertyMetadata(null, OnSourceChanged));


        /// <summary>
        /// 轴颜色
        /// </summary>
        public Brush AxisBackground
        {
            get { return (Brush)GetValue(AxisBackgroundProperty); }
            set { SetValue(AxisBackgroundProperty, value); }
        }
        public static readonly DependencyProperty AxisBackgroundProperty =
            DependencyProperty.Register("AxisBackground", typeof(Brush), typeof(MessageTimeline), new PropertyMetadata(Brushes.Orange));


        /// <summary>
        /// 圆圈常规颜色
        /// </summary>
        public Brush CircleNomalColor
        {
            get { return (Brush)GetValue(CircleNomalColorProperty); }
            set { SetValue(CircleNomalColorProperty, value); }
        }
        public static readonly DependencyProperty CircleNomalColorProperty =
            DependencyProperty.Register("CircleNomalColor", typeof(Brush), typeof(MessageTimeline), new PropertyMetadata(new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xFF, 0x4B, 0xB1, 0x5D))));


        /// <summary>
        /// 圆圈预警颜色
        /// </summary>
        public Brush CircleWarningColor
        {
            get { return (Brush)GetValue(CircleWarningColorProperty); }
            set { SetValue(CircleWarningColorProperty, value); }
        }
        public static readonly DependencyProperty CircleWarningColorProperty =
            DependencyProperty.Register("CircleWarningColor", typeof(Brush), typeof(MessageTimeline), new PropertyMetadata(new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xFF, 0xFB, 0xBC, 0x05))));


        /// <summary>
        /// 谷歌红
        /// </summary>
        public Brush CircleAlarmColor
        {
            get { return (Brush)GetValue(CircleAlarmColorProperty); }
            set { SetValue(CircleAlarmColorProperty, value); }
        }
        public static readonly DependencyProperty CircleAlarmColorProperty =
            DependencyProperty.Register("CircleAlarmColor", typeof(Brush), typeof(MessageTimeline), new PropertyMetadata(new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xFF, 0xEA, 0x42, 0x35))));




        /// <summary>
        /// 数据初始化时触发
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is MessageTimeline thisControl)
            {
                // 取消旧值的事件订阅
                if (e.OldValue is MessageDatas oldData)
                {
                    oldData.PropertyChanged -= thisControl.OnSourceDataChanged;
                }

                // 订阅新值的事件
                if (e.NewValue is MessageDatas newData)
                {
                    newData.PropertyChanged += thisControl.OnSourceDataChanged;
                }
                // 处理 Source 变更逻辑
                Console.WriteLine("Source object changed.");
            }
        }

        /// <summary>
        /// 数据改变时触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnSourceDataChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(MessageDatas.Messages) && this.Source != null)
            {
                if (!this.Source.Equals(_messageDatas))
                {
                    RefreshUI();
                }

            }
            _messageDatas = this.Source.Clone();
        }

        /// <summary>
        /// 刷新UI界面
        /// </summary>
        private void RefreshUI()
        {
            #region 设置
            double circularDotsdiameter = 25; // 圆点直径
            double timeTextFontSize = this.FontSize;
            double timeTextHeight = timeTextFontSize * 2.4;
            double messageFontSize = this.FontSize;
            double column1Width = timeTextFontSize * 6;
            double column2Width = 10;
            double column3Width = this.ActualWidth - column1Width - column2Width;
            #endregion

            #region 整理数据
            SingleMessage earliestMessage = this.Source.GetEarliestMessage();
            SingleMessage latestMessage = this.Source.GetLatestMessage();
            double singleMessageHeight = 50;
            #endregion

            #region 初始化控件
            Border border = new Border()
            {
                Background = this.Background,
            };
            Canvas canvas = new Canvas()
            {
                MinWidth = 100,
                MinHeight = 100,
            };
            border.Child = canvas;
            this.Content = border;
            #endregion
            #region 绘制轴
            // ①创建一个不规则图形
            Path path = new Path
            {
                Fill = this.AxisBackground,
            };
            // ②定义图形的几何路径
            PathGeometry geometry = new PathGeometry();
            // ③添加第一个不规则图案
            PathFigure figure = new PathFigure
            {
                StartPoint = new Point(column1Width, 0),
                IsFilled = true
            };
            // 添加各个顶点，形成不规则图形
            figure.Segments.Add(new LineSegment(new Point(column1Width + column2Width, 0), true));
            figure.Segments.Add(new LineSegment(new Point(column1Width + column2Width, this.ActualHeight), true));
            figure.Segments.Add(new LineSegment(new Point(column1Width, this.ActualHeight), true));
            figure.Segments.Add(new LineSegment(new Point(column1Width, 0), true));
            // 将图形路径添加到几何体
            geometry.Figures.Add(figure);
            path.Data = geometry;
            canvas.Children.Add(path);
            #endregion
            #region 绘制消息
            foreach (var item in this.Source.Messages)
            {
                double position = GetControlPosition(item.time, earliestMessage.time, latestMessage.time, this.ActualHeight);
                {
                    Border circle = new Border()
                    {
                        Width = circularDotsdiameter,  // 设置圆的直径
                        Height = circularDotsdiameter, // 设置圆的直径
                        Background = (item.type == Models.Common.AlarmLevel.None) ? this.CircleNomalColor : ((item.type == Models.Common.AlarmLevel.Warning) ? this.CircleWarningColor : this.CircleAlarmColor),
                        CornerRadius = new CornerRadius(circularDotsdiameter / 2),
                        BorderBrush = new SolidColorBrush(Color.FromArgb(0x80, 0xFF, 0xFF, 0xFF)), // 设置边框颜色
                        BorderThickness = new Thickness(5),   // 设置边框厚度
                        ToolTip = item.tips,
                    };
                    AnimationHelper.ApplyMouseEnterAnimation(circle,circle.Width / 2,circle.Height/2,1.5);
                    // 使用 Canvas.SetLeft 和 Canvas.SetTop 来设置圆的位置
                    Canvas.SetLeft(circle, column1Width + column2Width /2  - circularDotsdiameter / 2);
                    Canvas.SetTop(circle, position - circularDotsdiameter / 2);
                    canvas.Children.Add(circle);
                } // 圆点
                {
                    TextBlock textBlock = new TextBlock()
                    {
                        Text = item.time.ToString("yyyy/MM/dd\nHH:mm:ss"),
                        FontSize = timeTextFontSize,
                        Foreground = this.Foreground,
                        Height = timeTextHeight,
                        VerticalAlignment = VerticalAlignment.Center,
                        HorizontalAlignment = HorizontalAlignment.Center,
                    };
                    Canvas.SetLeft(textBlock, 0);
                    Canvas.SetTop(textBlock, position - timeTextHeight / 2);
                    canvas.Children.Add(textBlock);
                } // 时间文本
                {
                    Border messageBox = new Border()
                    {
                        CornerRadius = new CornerRadius(5),
                        Background = new SolidColorBrush(Color.FromArgb(0xAA, 0xFF, 0xFF, 0xFF)),
                        Width = column3Width - 10,
                        MinHeight = 20
                    };
                    StackPanel stackPanel = new StackPanel();
                    TextBlock title = new TextBlock()
                    {
                        Text = item.title,
                        FontSize = messageFontSize,
                        Foreground = this.Foreground,
                        FontWeight = FontWeights.Bold,
                        TextWrapping = TextWrapping.Wrap,
                        Margin = new Thickness(2),
                    };
                    TextBlock message = new TextBlock()
                    {
                        Text = item.message,
                        FontSize = messageFontSize,
                        Foreground = this.Foreground,
                        TextWrapping = TextWrapping.Wrap,
                        Margin = new Thickness(2),
                    };
                    stackPanel.Children.Add(title);
                    stackPanel.Children.Add(message);
                    messageBox.Child = stackPanel;
                    AnimationHelper.ApplyMouseEnterAnimation(messageBox,enlargeScale:1.1);
                    Canvas.SetLeft(messageBox, column1Width + column2Width + 15);
                    Canvas.SetTop(messageBox, position - circularDotsdiameter / 2);
                    canvas.Children.Add(messageBox);
                } // 标题和正文
            }
            #endregion
        }

        /// <summary>
        /// 获取控件位置
        /// </summary>
        /// <param name="time"></param>
        /// <param name="minTime"></param>
        /// <param name="maxTime"></param>
        /// <param name="canvasHeight"></param>
        /// <returns></returns>
        private static double GetControlPosition(DateTime time,DateTime minTime,DateTime maxTime, double canvasHeight)
        {
            double realPosition = 0;
            if (minTime >= maxTime)
            {
                realPosition = canvasHeight - canvasHeight / 2;
            }
            else
            {
                double k = (time - minTime).TotalMilliseconds / (maxTime - minTime).TotalMilliseconds;
                realPosition = canvasHeight - k * canvasHeight;
            }
            return realPosition;
        }
    }
}
